/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>

#ifdef ADAPTER_BT_L0_SUPPORT
#include "ohos_bt_log.h"
#else
#include "log.h"
#endif
#include "bts_le_gap.h"
#include "ohos_bt_gap.h"

bool ble_enable_flag = false;

int InitBtStack(void) {
  LOG_PRINT("[bluetooth] InitBtStack");
  return ERRCODE_BT_SUCCESS;
}

int EnableBtStack(void) {
    LOG_PRINT("[bluetooth] EnableBtStack");
    errcode_t ret = ERRCODE_BT_FAIL;
    ret = enable_ble();
    if (ERRCODE_BT_SUCCESS == ret) {
        ble_enable_flag = true;
    }
    return ret;
}

int DisableBtStack(void) {
    LOG_PRINT( "[bluetooth] DisableBtStack");
    errcode_t ret = ERRCODE_BT_FAIL;
    ret = disable_ble();
    if (ERRCODE_BT_SUCCESS == ret) {
        ble_enable_flag = false;
    }
    return ret;
}

int SetLocalName(unsigned char *localName, unsigned char length){
  return SetDeviceName(localName, length);
}

int SetDeviceName(const char *name, unsigned int len){
    LOG_PRINT( "[bluetooth] SetDeviceName");
    errcode_t ret = ERRCODE_BT_FAIL;
    ret = gap_ble_set_local_name(name, len);
    if (ret != ERRCODE_BT_SUCCESS) {
    LOG_PRINT( "[bluetooth] gap_ble_set_local_name ret:%u", ret);
    }
    return ret;
}


bool IsBleEnabled(void)
{
    return ble_enable_flag;
}

bool GetLocalAddr(unsigned char *mac, unsigned int len)
{
    HILOG_DEBUG("[bluetooth] GetLocalAddr");
    errcode_t ret = ERRCODE_BT_FAIL;
    bd_addr_t bleAddr;
    ret = gap_ble_get_local_addr(&bleAddr);
    if (ERRCODE_BT_SUCCESS == ret) {
        memcpy_s(mac, len, bleAddr.addr, BD_ADDR_LEN);
        return true;
    } else {
        return false;
    }
}

int GetBtState(void) {
    LOG_PRINT( "[bluetooth] ReadBtMacAddr");
    if(IsBleEnabled()){
        return 1;
    }
    return 0;
}

int ReadBtMacAddr(unsigned char *mac, unsigned int len) {
  LOG_PRINT( "[bluetooth] ReadBtMacAddr");
  return GetLocalAddr(mac, len);
}
